<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <h1>图片上传</h1>
    <!-- 文件上传文件时，需改变属性enctype = “multipart/form-data”  -->
    <input hidden id="imgInput" type="file" name="imgfile">
    <label for="imgInput">选择文件</label>
    <button class="btn">上传</button>
    <div>
        <h3>预览图片</h3>
        <img id="yulan" alt="" width="200">
    </div>
    <script src="/javascripts/jquery.js"></script>

    <script>
        let formDataObj; let file
        $('#imgInput').change(function (e) {
            console.log(this.files)
            file = this.files[0];
            // 预览图片
            // 创建预览图片地址
            let httpUrl = window.webkitURL.createObjectURL(file)
            $('#yulan').attr('src', httpUrl)
            // 创建formData对象
            formDataObj = new FormData()
            formDataObj.append("imgfile", file);
        })
        $('.btn').click(function () {
            $.ajax({
                url: '/imgUpload',
                method: 'POST',
                data: formDataObj,
                processData: false,
                contentType: false
            }).then(res => {
                $("body").append("<h1>上传成功</h1>")
            })
        })
    </script>
</body>

</html>